using System;
using System.Collections.Generic;
using System.IO;

namespace Sfd.Services.Synchronizers
{
    public class FileSynchronizer
    {
        public string RootFolder { get; private set; }

        public FileSynchronizer(string rootFolder)
        {
            RootFolder = rootFolder;
        }

        public Dictionary<string, SyncItem> GetSyncItems()
        {
            var syncItems = new Dictionary<string, SyncItem>();

            SearchSubFolders(syncItems, RootFolder);

            return syncItems;
        }

        public Dictionary<string, SyncItem> GetSyncItems(IEnumerable<string> files)
        {
            var syncItems = new Dictionary<string, SyncItem>();

            foreach (var file in files)
            {
                var folderName = Path.GetDirectoryName(file);

                if (folderName != null && File.Exists(file) && folderName.ToLower().StartsWith(RootFolder.ToLower()))
                {
                    var syncItem = CreateSyncItem(file);
                    syncItems.Add(syncItem.Key, syncItem);
                }
            }

            return syncItems;
        }

        private void SearchSubFolders(IDictionary<string, SyncItem> syncItems, string folder)
        {
            foreach (var file in Directory.GetFiles(folder))
            {
                var syncItem = CreateSyncItem(file);
                syncItems.Add(syncItem.Key, syncItem);
            }

            foreach (var subFolder in Directory.GetDirectories(folder))
                SearchSubFolders(syncItems, subFolder);
        }

        private FileSyncItem CreateSyncItem(string fileName)
        {
            return new FileSyncItem
            {
                FileName = fileName,
                Key = GetKey(fileName),
                LastModificationDateTicks = File.GetLastWriteTimeUtc(fileName).Ticks,
                Length = (new FileInfo(fileName)).Length
            };
        }

        public string GetKey(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException("fileName");

            if (!fileName.ToLower().StartsWith(RootFolder.ToLower()))
                throw new ArgumentException("Le fichier n'est pas dans le dossier Root", "fileName");

            return fileName.Substring(RootFolder.Length + 1).Replace(@"\", @"/").ToLower();
        }
    }
}